package com.moonshineproject.plugin.svn.commands
{
	import com.moonshineproject.plugin.project.event.ProjectEvent;
	import com.moonshineproject.plugin.project.vo.ProjectVO;
	
	import flash.desktop.NativeProcess;
	import flash.desktop.NativeProcessStartupInfo;
	import flash.events.Event;
	import flash.events.NativeProcessExitEvent;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.utils.IDataInput;
	import flash.utils.Timer;
	
	public class CheckoutCommand extends SVNCommandBase
	{
		public function CheckoutCommand(executable:File, root:File)
		{
			super(executable, root);
		}
		
		public function checkout(dir:File, url:String):void
		{
			if (runningForFile)
			{
				error("Currently running, try again later.");
				return;
			}
			
			notice("Trying to check out %s. May take a while.", url);
			
			customInfo = new NativeProcessStartupInfo();
			customInfo.executable = executable;
			
			var args:Vector.<String> = new Vector.<String>();
			 
			args.push("checkout");
			args.push(url);
			
			customInfo.arguments = args;
			customInfo.workingDirectory = dir;
			
			customProcess = new NativeProcess();
			customProcess.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, svnError);
			customProcess.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, svnOutput);
			customProcess.addEventListener(NativeProcessExitEvent.EXIT, svnExit);
			customProcess.start(customInfo);
			
			runningForFile = dir;
		}
		
		protected function svnError(event:ProgressEvent):void
		{
			var output:IDataInput = customProcess.standardError;
			var data:String = output.readUTFBytes(output.bytesAvailable);
	
			if (serverCertificatePrompt(data)) return;
	
			error("%s", data);
		}
		
		protected function svnOutput(event:ProgressEvent):void
		{ 
			var output:IDataInput = customProcess.standardOutput;
			var data:String = output.readUTFBytes(output.bytesAvailable);
			
			notice("%s", data);
		}
		
		protected function svnExit(event:NativeProcessExitEvent):void
		{
			if (event.exitCode == 0)
			{
				var p:ProjectVO = new ProjectVO(runningForFile);
				dispatcher.dispatchEvent(
					new ProjectEvent(ProjectEvent.ADD_PROJECT, p)
				);
			}
			else
			{
				// Checkout failed
			}
			
			runningForFile = null;
			customProcess = null;
		}
		
	}
}